package com.dtw.ditouwang.ui.mine;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;

import com.bumptech.glide.Glide;
import com.dtw.ditouwang.R;
import com.dtw.ditouwang.beans.CommonBean;
import com.dtw.ditouwang.beans.SetUserHeadBackBean;
import com.dtw.ditouwang.beans.UserBean;
import com.dtw.ditouwang.databinding.ActivityUserinfoBinding;
import com.dtw.ditouwang.repositories.UserRepository;
import com.dtw.ditouwang.ui.BaseActivity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserInfoActivity extends BaseActivity implements View.OnClickListener {
    private final int CodeCamera = 100, CodePicture = 101;
    ActivityUserinfoBinding activityUserinfoBinding;
    UserBean.DataBean userBean;
    AlertDialog alertdialog;
    ImageView headImage;
    EditText age;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityUserinfoBinding = DataBindingUtil.setContentView(this, R.layout.activity_userinfo);
        initData();
    }

    private void initData() {
        headImage = findViewById(R.id.img_head);
        age = findViewById(R.id.edit_age);
        enableBack();
        setTitle("个人信息");
        setSubTitle("保存", this);
        userBean = UserRepository.getInstance().getUserBean().getData();
        activityUserinfoBinding.setUser(userBean);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CodeCamera:
                    Bitmap photo = (Bitmap) data.getExtras().get("data");
                    Glide.with(headImage).load(photo).into(headImage);
                    try {
                        File imgFile = new File(getExternalFilesDir(Environment.DIRECTORY_DCIM), System.currentTimeMillis() + ".jpg");
                        Glide.with(headImage).load(imgFile).into(headImage);
                        UserBean userBean=UserRepository.getInstance().getUserBean();
                        userBean.getData().setHead(imgFile.getPath());
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imgFile));
                        photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        bos.flush();
                        bos.close();
                        uploadUserHead(imgFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case CodePicture:
                    Uri selectedImage = data.getData();
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
                        Glide.with(headImage).load(bitmap).into(headImage);
                        File imgFile = new File(getExternalFilesDir(Environment.DIRECTORY_DCIM), System.currentTimeMillis() + ".jpg");
                        UserBean userBean=UserRepository.getInstance().getUserBean();
                        userBean.getData().setHead(imgFile.getPath());
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imgFile));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        bos.flush();
                        bos.close();
                        uploadUserHead(imgFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_sub_title:
                showProgress();
                userBean.setAge(TextUtils.isEmpty(age.getText().toString())?"0":age.getText().toString());
                webApi.setUserInfo(userBean.getId(), userBean.getName(), userBean.getBirthdate(),
                        ((RadioButton) findViewById(R.id.radio_man)).isChecked() ? 1 : 2, userBean.getAge(), userBean.getNickname(),
                        userBean.getHobby(), userBean.getAddress(), userBean.getStature(), userBean.getConstellation()).enqueue(new Callback<CommonBean>() {
                    @Override
                    public void onResponse(Call<CommonBean> call, Response<CommonBean> response) {
                        closeProgress();
                        if (response.body() != null) {
                            if (response.body().isResult()) {
                                showToast("修改成功");
                                onBackPressed();
                            } else {
                                showToast(response.body().getMsg());
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonBean> call, Throwable t) {
                        showToast("服务器异常");
                    }
                });
                break;
            case R.id.view_head:
                View view = LayoutInflater.from(this).inflate(R.layout.dialog_choose_image, null);
                alertdialog = new AlertDialog.Builder(this, R.style.BottomDialog).setView(view).show();
                Window window = alertdialog.getWindow();
                window.setGravity(Gravity.BOTTOM); // 此处可以设置dialog显示的位置
                ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                view.findViewById(R.id.text_camera).setOnClickListener(this);
                view.findViewById(R.id.text_picture).setOnClickListener(this);
                view.findViewById(R.id.text_cancle).setOnClickListener(this);
                break;
            case R.id.text_camera:
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CodeCamera);
                alertdialog.dismiss();
                break;
            case R.id.text_picture:
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, CodePicture);
                alertdialog.dismiss();
                break;
            case R.id.text_cancle:
                if (alertdialog != null && alertdialog.isShowing()) {
                    alertdialog.dismiss();
                }
                break;
        }
    }

    private void uploadUserHead(File imagefile) {
        final RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), imagefile);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("imghaed", imagefile.getName(), requestFile);

        webApi.uploadHead(filePart).enqueue(new Callback<CommonBean>() {
            @Override
            public void onResponse(Call<CommonBean> call, Response<CommonBean> response) {
                if (response.body().isResult() && response.body().getData() != null) {
                    UserRepository.getInstance().getUserBean().getData().setHead((String)response.body().getData());
                    setUserHead(userBean.getId(), (String) response.body().getData());
                } else {
                    showToast(response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<CommonBean> call, Throwable t) {

            }
        });
    }

    private void setUserHead(int userID, String imagePath) {
        webApi.setUserHead(userID, imagePath).enqueue(new Callback<SetUserHeadBackBean>() {
            @Override
            public void onResponse(Call<SetUserHeadBackBean> call, Response<SetUserHeadBackBean> response) {

            }

            @Override
            public void onFailure(Call<SetUserHeadBackBean> call, Throwable t) {

            }
        });
    }
}
